<template>
  <div class="video_container">
    <!-- :key="video_src" -->
    <video-player
      class="video-player vjs-custom-skin"
      ref="videoPlayer"
      :playsinline="true"
      :options="playerOptions"
      @ready="onVideoReadied"
      @ended="onVideoEnded"
    >
      <!-- <source :src="video_src" type="video/mp4" /> -->
    </video-player>
    <!-- <video :src="video_src"></video> -->
    <!-- <collapse-aside></collapse-aside> -->
    <div v-if="showOverlay" class="overlay">
      <div class="countdown">{{ countdown }}秒后自动播放下一个视频</div>
      <button @click="replayVideo">重新播放</button>
    </div>
    <el-button
      @click="nextSection"
      :style="{ 'margin-top': '20px' }"
      type="primary"
      >下一节</el-button
    >
    <el-button @click="dialogVisible = true" type="primary"
      >打开趣味游戏</el-button
    >
    <el-dialog title="趣味游戏" :visible.sync="dialogVisible" width="50%">
      <pop-game></pop-game>
    </el-dialog>
    <file-inline></file-inline>
  </div>
</template>

<script>
import { videoPlayer } from "vue-video-player";
import FileInline from "@/components/FileInline.vue";
import "video.js/dist/video-js.css";
import { mapGetters, mapActions } from "vuex";
import PopGame from "@/components/PopGame.vue";
// import { Loading } from "element-ui";

export default {
  components: { videoPlayer, FileInline, PopGame },
  data() {
    return {
      playerOptions: {
        playbackRates: [0.5, 1.0, 1.5, 2.0], // 可选的播放速度
        autoplay: true, // 如果为true,浏览器准备好时开始回放
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 是否视频一结束就重新开始。
        preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: "zh-CN",
        aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [
          {
            type: "video/mp4", // 这里的种类支持很多种：基本视频格式、直播、流媒体等，具体可以参看git网址项目
            src: "", // url地址
          },
        ],
        poster: "", // 封面地址
        notSupportedMessage: "此视频暂无法播放，请稍后再试", // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true, // 当前时间和持续时间的分隔符
          durationDisplay: true, // 显示持续时间
          remainingTimeDisplay: true, // 是否显示剩余时间功能
          fullscreenToggle: true, // 是否显示全屏按钮
        },
      },
      showOverlay: false,
      countdown: 5,
      watched: false,
      isLoading: false,
      dialogVisible: false,
    };
  },
  watch: {
    video_src(newData) {
      // console.log(newData);
      // console.log('aaa')
      this.playerOptions.sources[0].src = newData;
      // this.isLoading = true;
    },
  },
  computed: {
    video_src() {
      return this.$store.state.studyAbout.video.url;
    },
    ...mapGetters("studyAbout", ["next"]),
  },
  methods: {
    ...mapActions("studyAbout", ["getStudyContent"]),
    handleLoadedData() {
      this.isLoading = false;
      // 尝试自动播放视频
      this.$refs.videoPlayer.play();
    },
    onVideoReadied() {
      // this.loadingInstance.close();
    },
    nextSection() {
      // 下一节的回调
      // console.log("下一节");
      // this.$store.dispatch("studyAbout/getStudyContent", "1-2");
      // 获取下一个section_id，然后改变地址栏，改变vuex中维护的section_id，然后其他的都不用管
      // const next_section =  this.$store.getters.studyAbout.next();
      // console.log(this.$store.getters["studyAbout/next"]);
      // console.log('next_section: ', next_section);
      // 改变地址栏
      // this.$router.replace() 167 + 剧场 + 完结
      // 维护section_id
      if (this.next == -1) {
        alert("无法下一个");
        return;
      } else {
        // 路由改变
        this.$router.replace({
          path: "/study",
          query: {
            section_id: this.next,
          },
        });
      }
      // 维护vuex
      this.getStudyContent(this.next);
    },
    onVideoEnded() {
      // 视频播放完成时触发
      // console.log("视频播放完成");
      this.watched = true;
      const { currentTime } = this.videoDOM;
      const { watched } = this;
      this.$store.commit("studyAbout/SET_VIDEO", { currentTime, watched });
      // this.showOverlay = true;
      // this.startCountdown();
    },
    startCountdown() {
      if (this.countdown > 0) {
        setTimeout(() => {
          this.countdown -= 1;
          this.startCountdown();
        }, 1000);
      } else {
        // this.callBack();
        this.nextSection();
        this.showOverlay = false;
      }
    },
    callBack() {
      // 倒计时结束时调用回调函数
      console.log("倒计时结束");
    },
    replayVideo() {
      // 重新播放视频
      this.showOverlay = false;
      this.countdown = 5;
      // this.$refs.videoPlayer.replay();
      this.$refs.videoPlayer.$refs.video.currentTime = 0;
      this.$refs.videoPlayer.$refs.video.play();
    },
    handleLoadedData() {
      this.isLoading = false;
    },
  },
  created() {
    // console.log(document.querySelector("video"));
    this.$nextTick(() => {
      this.videoDOM = document.querySelector("video");
      // console.log(this.videoDOM);
      // this.videoDOM.addEventListener("ended", function () {
      //   console.log("视频播放完成");
      // });
    });
    this.playerOptions.sources[0].src = this.video_src;
    // this.loadingInstance = Loading.service({
    //   lock: true,
    //   text: "正在获取数据...",
    //   spinner: "el-icon-loading",
    //   background: "rgba(0, 0, 0, 0.7)",
    // });
  },
  beforeDestroy() {
    const { currentTime } = this.videoDOM;
    const { watched } = this;
    this.$store.commit("studyAbout/SET_VIDEO", { currentTime, watched });
  },
};
</script>

<style lang="less" scoped>
.video_container {
  width: 70%;
  // height: 90%;
  margin: 20px auto;
  position: relative;
  .video-player {
    :deep(.vjs-big-play-button) {
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      margin: auto;
    }
  }
}
.overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: calc(100% - 60px);
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: white;
}
.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.loading-spinner {
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3498db;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  animation: spin 2s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.loading-text {
  color: #f3f3f3;
  margin-top: 10px;
}
.el-dialog__wrapper {
  :deep(.el-dialog__body) {
    height: 500px;
  }
}
</style>